package com.mk.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

@SuppressWarnings("all")
public class EncyUtils {
    public static final String DEFAULT_CODING = "utf-8";

    /**
     * MD5加密，自动追加key
     * 适用于大多数加密情况（如密码、密码提示等）
     *
     * @param s
     * @return
     */
    public static String MD5(String s) {
        return MD5(s, "eme909014123561236jkwsdfjdw");
    }

    /**
     * MD5加密，手动指定加密key
     *
     * @param s
     * @param key
     * @return
     */
    public static String MD5(String s, String key) {
        s += key;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes(StandardCharsets.UTF_8);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成六位数随机密码
     *
     * @return
     */
    public static String getInitPassWord() {
        int i = (int) ((Math.random() * 9 + 1) * 100000);
        return String.valueOf(i);
    }

    /**
     * 解密
     *
     * @param encrypted
     * @param seed
     * @return
     * @throws Exception
     */
    public static String AESDecrypt(String encrypted, String seed) {
        try {
            byte[] keyb = seed.getBytes(StandardCharsets.UTF_8);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(keyb);
            SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
            Cipher dcipher = Cipher.getInstance("AES");
            dcipher.init(Cipher.DECRYPT_MODE, skey);

            byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
            return new String(clearbyte);
        } catch (Exception ignored) {

        }
        return null;
    }

    /**
     * 加密
     *
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String AESEncrypt(String content, String key) {
        try {
            byte[] input = content.getBytes(StandardCharsets.UTF_8);

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(key.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skc);

            byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
            int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
            ctLength += cipher.doFinal(cipherText, ctLength);

            return parseByte2HexStr(cipherText);
        } catch (Exception ignored) {

        }
        return null;
    }

    /**
     * 字符串转字节数组
     *
     * @param hexString
     * @return
     * @author lmiky
     * @date 2014-2-25
     */
    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        }
        return result;
    }

    /**
     * 字节转16进制数组
     *
     * @param buf
     * @return
     * @author lmiky
     * @date 2014-2-25
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aBuf : buf) {
            String hex = Integer.toHexString(aBuf & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
